<template>
	<div class="product-list">
		<!--搜索表单-->
		<div class="common-seach-wrap">
			<el-tabs v-model="activeName" @tab-change="handleClick">
				<el-tab-pane label="出售中" name="sell">
					<template #label>
						<span>出售中
							<el-tag size="small">{{ product_count.sell }}</el-tag></span>
					</template>
				</el-tab-pane>
				<el-tab-pane label="仓库中" name="lower">
					<template #label>
						<span>仓库中
							<el-tag size="small">{{ product_count.lower }}</el-tag></span>
					</template>
				</el-tab-pane>
				<el-tab-pane label="回收站" name="recovery">
					<template #label>
						<span>回收站
							<el-tag size="small">{{ product_count.recovery }}</el-tag></span>
					</template>
				</el-tab-pane>
				<el-tab-pane label="库存紧张" name="stock">
					<template #label>
						<span>库存紧张
							<el-tag size="small">{{ product_count.stock }}</el-tag></span>
					</template>
				</el-tab-pane>
				<!-- <el-tab-pane label="草稿箱" name="draft">
					<template #label>
						<span>草稿箱
							<el-tag size="small">{{ product_count.draft }}</el-tag></span>
					</template>
				</el-tab-pane>
				<el-tab-pane label="待审核" name="audit">
					<template #label>
						<span>待审核
							<el-tag size="small">{{ product_count.audit }}</el-tag></span>
					</template>
				</el-tab-pane>
				<el-tab-pane label="未通过" name="no_audit">
					<template #label>
						<span>未通过
							<el-tag size="small">{{ product_count.no_audit }}</el-tag></span>
					</template>
				</el-tab-pane> -->
			</el-tabs>

			<el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
				<el-form-item label="销量筛选">
					<el-select size="small" style="width:168px" v-model="searchForm.salerNumberSort" clearable placeholder="请选择">
						<el-option label="升序" value="1"></el-option>
						<el-option label="降序" value="2"></el-option>	
					</el-select>
				</el-form-item>

				<el-form-item label="商品分类">
					<el-select size="small" style="width:168px" v-model="searchForm.category_id" clearable placeholder="所有分类">
						<el-option label="全部" value="0"></el-option>
						<el-option v-for="(item, index) in categoryList" :key="index" :label="item.name"
							:value="item.category_id"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="商品名称"><el-input style="width:180px" clearable size="small" v-model="searchForm.product_name"
						placeholder="请输入商品名称"></el-input></el-form-item>

				<el-form-item label="商品编码">
					<el-input clearable style="width:180px" size="small" v-model="searchForm.sku"
					placeholder="请输入商品编码"></el-input>
				</el-form-item>

				

				<el-form-item>
					<el-button size="small" type="primary" icon="Search" @click="onSubmit">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button size="small" type="primary" icon="Plus" @click="addClick"
						v-auth="'/product/product/add'">添加商品</el-button>
				</el-form-item>

				<el-form-item>
					<el-upload action ref="batchAddFile" class="upload-demo" :limit="1" :show-file-list="false"
						:before-upload="beforeUpload" :http-request="batchAddProduct">
						<el-button icon="Upload" type="primary">批量导入商品</el-button>
					</el-upload>
				</el-form-item>

				<el-form-item>
					<el-button icon="Download" type="primary" @click="downloadExcel">下载更新模板</el-button>
				</el-form-item>

				<el-form-item>
					<el-upload action ref="batchUpdateFile" class="upload-demo" :limit="1" :show-file-list="false"
						:before-upload="beforeUpload" :http-request="batchUpdateProduct">
						<el-button icon="Upload" type="primary">批量更新商品</el-button>
					</el-upload>
				</el-form-item>

				<el-form-item>
					<el-button size="small" type="danger" icon="Delete" :disabled="this.selectedRows.length == 0"
						@click="batchDel">批量删除商品</el-button>
				</el-form-item>
			</el-form>
		</div>

		<!--添加产品-->
		<!-- <div class="common-level-rail " v-if="supplier.status == 0">
			<el-button size="small" type="primary" icon="Plus" @click="addClick"
				v-auth="'/product/product/add'">添加产品</el-button>

			<el-upload style="margin-left: 10px" ref="batchAddFile" class="upload-demo" :limit="1"
				:show-file-list="false" :before-upload="beforeUpload" :http-request="batchAddProduct">
				<el-button icon="Upload" type="primary">批量导入产品</el-button>
			</el-upload>

			<el-upload style="margin-left: 10px" ref="batchAddFile" class="upload-demo" :limit="1"
				:show-file-list="false" :before-upload="beforeUpload" :http-request="batchUpdateProduct">
				<el-button icon="Upload" type="primary">批量更新产品</el-button>
			</el-upload>

			<el-button style="margin-left: 10px" size="small" type="danger" icon="Delete"
				:disabled="this.selectedRows.length == 0" @click="batchDel">批量删除</el-button>
		</div> -->
		<!-- <div class="common-level-rail" v-if="supplier.status != 0">
			<el-button size="small" type="primary" icon="Plus" v-auth="'/product/product/add'"
				disabled="true">添加产品</el-button>
			<span class="red pl16" v-if="supplier.status == 10">正在退保证金</span>
			<span class="red pl16" v-if="supplier.status == 20">未交纳保证金，请到移动端交纳</span>
		</div> -->
		<!--内容-->
		<div class="product-content">
			<div class="table-wrap">
				<el-table ref="table" size="small" :data="tableData" border style="width: 100%" v-loading="loading"
					@selection-change="handleSelectionChange">
					>
					<el-table-column type="selection" width="50" align="center" />
					<!-- <el-table-column type="index" label="序号" width="50" align="center" /> -->
					<el-table-column prop="product_name" show-overflow-tooltip label="产品" width="418px">
						<template #default="scope">
							<div class="product-info">
								<div class="pic">
									<img v-img-url="scope.row.image[0].file_path" alt="" />
								</div>
								<div class="info">
									<div class="name">{{ scope.row.product_name }} </div>
									<div class="">商品编码：{{ scope.row.product_sku.product_no || '无' }}</div>
									<span class="price">￥{{ scope.row.product_price }}</span>
									
									<!-- <div class="price" v-if="scope.row.audit_status == 20">
										未通过原因：{{ scope.row.audit_remark }}
									</div>
									<div class="price" v-if="scope.row.audit_status == 30">
										强制下架：{{ scope.row.audit_remark }}
									</div> -->
								</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="category.name" show-overflow-tooltip label="分类" align="center"></el-table-column>
			
					<el-table-column prop="sku" show-overflow-tooltip label="SKU规格" align="center" width="128">
						<template #default="scope">
							<div class="sku-item" v-for="(i,index) in scope.row.sku" :key="index">
								<!-- <span  class="sku-item-option ">{{ i.product_no }} </span> -->
								<span class="sku-item-option "> {{ i.spec_sku_value }}</span>
							</div>
						</template>
					</el-table-column>

					<el-table-column prop="sku" show-overflow-tooltip label="SKU库存" align="center" width="128">
						<template #default="scope">
							<div class="sku-item" v-for="(i,index) in scope.row.sku" :key="index">
								<span  class="sku-item-option " v-if="i.unlimit == 1">不限量 </span>
								<span  class="sku-item-option " v-else> {{ i.stock_num }}</span>
							</div>
						</template>
					</el-table-column>


					<el-table-column prop="sku" show-overflow-tooltip label="SKU库位" align="center"  width="128">
						<template #default="scope">
							<div class="sku-item" v-for="(i,index) in scope.row.sku" :key="index">
								<span  class="sku-item-option " >{{ i.storehouse || '无' }}</span>
							</div>
						</template>
					</el-table-column>


					<el-table-column prop="sku" show-overflow-tooltip label="SKU保质期" align="center" width="128">
						<template #default="scope">
							<div class="sku-item" v-for="(i,index) in scope.row.sku" :key="index">
								<span  class="sku-item-option " >{{ i.shelf_life || '无' }}</span>
							</div>
						</template>
					</el-table-column>
	
					<!-- <el-table-column prop="view_times" label="点击数" align="center"></el-table-column>
					<el-table-column prop="product_status.text" label="商品属性" align="center">
						<template #default="scope">
							<span v-if="scope.row.is_virtual == 0">实物商品</span>
							<span v-if="scope.row.is_virtual == 1" class="green">虚拟商品</span>
						</template>
					</el-table-column> -->
					<el-table-column prop="sales_actual" label="实际销量" align="center" width="80"></el-table-column>
					<el-table-column prop="create_time" label="发布时间" align="center" width="138"></el-table-column>
					<el-table-column fixed="right" label="操作" align="center" width="270">
						<template #default="scope" v-if="supplier.status == 0">
							<div>
								<el-button @click="editClick(scope.row)" link type="primary" size="small"
									v-auth="'/product/product/edit'">编辑商品</el-button>

								<el-button @click="copyClick(scope.row)" link type="primary" size="small"
									v-auth="'/product/product/copy'">一键复制</el-button>

								<el-button v-if="activeName == 'recovery'" @click="changeStatus(scope.row, 20)" link
									type="primary" size="small" v-auth="'/product/product/state'">恢复</el-button>

								<el-button v-if="activeName == 'lower'" @click="changeStatus(scope.row, 10)" link
									type="primary" size="small" v-auth="'/product/product/state'">立即上架</el-button>

								<el-button v-if="activeName == 'sell'" @click="changeStatus(scope.row, 20)" link
									type="danger" size="small" v-auth="'/product/product/state'">立即下架</el-button>

								<el-button @click="delClick(scope.row)" link type="danger" size="small"
									v-auth="'/product/product/delete'">删除商品</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<!--分页-->
		<div class="pagination">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
				:current-page="curPage" :page-size="pageSize" layout="total, prev, pager, next, jumper"
				:total="totalDataNumber"></el-pagination>
		</div>
	</div>
</template>

<script>
import {
	productList,
	delProduct,
	changeStatus,
	apiBatchAddProduct,
	apiBatchUpdateProduct,
	apiBatchDelProduct,
	apiBatchExportProduct
} from "@/api/product.js";

import {
	useUserStore
} from "@/store";

import { isExcelFile } from "@/utils/validate.js";
export default {
	components: {},
	data() {
		return {
			/*切换菜单*/
			activeName: "sell",
			/*切换选中值*/
			activeIndex: "0",
			/*是否正在加载*/
			loading: true,
			/*一页多少条*/
			pageSize: 10,
			/*一共多少条数据*/
			totalDataNumber: 0,
			/*当前是第几页*/
			curPage: 1,
			/*搜索参数*/
			searchForm: {
				product_name: "",
				category_id: "",
				sku:"",
				salerNumberSort: "",
			},
			/*列表数据*/
			tableData: [],
			/*全部分类*/
			categoryList: [],
			supplier: [],
			/*统计数据*/
			product_count: {},
			// 列表选中项
			selectedRows: [],
		};
	},
	created() {
		/*获取列表*/
		this.getData();
	},
	methods: {
		downloadExcel(){
			const userStore = useUserStore();
			const {
				token
			} = userStore;

			let hasToken = "";
			if (token) {
				hasToken = token;
			}
			let params = {
                ...this.searchForm,
				type:'sell',
				token:hasToken
            };
			delete params.salerNumberSort 
			delete params.page 
			delete params.list_rows
			let url = "/index.php/supplier/product.product/export";
			this.$filter.onExportFunc(url, params);
		},


		// 列表选中项勾选变化
		handleSelectionChange(val) {
			this.selectedRows = val;
		},

		// 上传文件校验
		beforeUpload(file) {
			if (!isExcelFile(file.name)) {
				ElMessage.error("请上传excel文件!");
				return false;
			}
		},


		// 导出商品模板
		async exportProduct() {
			let params = {
                ...this.searchForm,
				type:'sell'
            };
			let data = await apiBatchExportProduct(params);
			console.log(data)

			const url = window.URL.createObjectURL(new Blob([data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', ); // 设置下载的文件名
                document.body.appendChild(link); // 需要添加到文档中
                link.click(); // 触发下载
                document.body.removeChild(link); // 下载后移除链接

			// if (data.code == 1) {
			// 	ElMessage.success(data.msg);

			// } else {
			// 	ElMessage.error("导出失败!");
			// }
		},

		// 批量上传商品
		async batchAddProduct(request) {
			const formData = new FormData();
			formData.append("iFile", request.file);
			const loading = ElLoading.service({
				lock: true,
				text: "文件上传中,请稍候...",
				background: "rgba(0, 0, 0, 0.7)",
			});
			let data = await apiBatchAddProduct(formData);

			if (data.code == 1) {
				ElMessage.success(data.msg);
				this.onSubmit();
			} else {
				ElMessage.error("上传失败!");
			}
			this.$refs.batchAddFile.clearFiles();
			loading.close();
		},

		// 批量更新商品
		async batchUpdateProduct(request) {
			const formData = new FormData();
			formData.append("iFile", request.file);
			const loading = ElLoading.service({
				lock: true,
				text: "文件上传中,请稍候...",
				background: "rgba(0, 0, 0, 0.7)",
			});
			let data = await apiBatchUpdateProduct(formData);
			if (data.code == 1) {
				ElMessage.success(data.msg);
				this.onSubmit();
			} else {
				ElMessage.error("上传失败!");
			}
			this.$refs.batchUpdateFile.clearFiles();
			loading.close();
		},

		// 批量删除操作
		batchDel() {
			ElMessageBox.confirm("是否删除选中项?", "提示", {
				type: "warning",
			}).then(() => {
				this.batchDelProduct();
			});
		},

		// 批量删除接口
		async batchDelProduct() {
			let arr = [];
			this.selectedRows.forEach((x) => {
				arr.push(x.product_id);
			});
			let params = {
				ids: arr.join(","),
			};
			let data = await apiBatchDelProduct(params);
			if (data.code == 1) {
				ElMessage.success(data.msg);
				this.selectedRows = [];
				this.$refs.table.clearSelection();
				this.onSubmit();
			} else {
				ElMessage.error("删除失败!");
			}
		},

		/*选择第几页*/
		handleCurrentChange(val) {
			let self = this;
			self.loading = true;
			self.curPage = val;
			self.getData();
		},

		/*每页多少条*/
		handleSizeChange(val) {
			this.pageSize = val;
			this.getData();
		},

		/*切换菜单*/
		handleClick(tab, event) {
			let self = this;
			self.curPage = 1;
			self.getData();
		},

		/*获取列表*/
		getData() {
			let self = this;
			let Params = self.searchForm;
			Params.page = self.curPage;
			Params.list_rows = self.pageSize;
			Params.type = self.activeName;
			self.loading = true;
			productList(Params, true)
				.then((data) => {
					self.loading = false;
					self.tableData = data.data.list.data;
					self.categoryList = data.data.category;
					self.totalDataNumber = data.data.list.total;
					self.supplier = data.data.supplier;
					self.product_count = data.data.product_count;
				})
				.catch((error) => {
					self.loading = false;
				});
		},

		/*搜索查询*/
		onSubmit() {
			this.curPage = 1;
			this.getData();
		},

		/*打开添加*/
		addClick() {
			this.$router.push("/product/product/add");
		},

		/*打开编辑*/
		editClick(row) {
			this.$router.push({
				path: "/product/product/edit",
				query: {
					product_id: row.product_id,
					scene: "edit",
				},
			});
		},

		/*打开复制*/
		copyClick(row) {
			this.$router.push({
				path: "/product/product/edit",
				query: {
					product_id: row.product_id,
					scene: "copy",
				},
			});
		},

		/*单项删除*/
		delClick: function (row) {
			let self = this;
			let msg = "";
			if (row.product_status == 30) {
				msg = "删除后不可恢复，确认删除该记录吗?";
			} else {
				msg = "删除后将移动到回收站，确定删除该记录吗?";
			}
			ElMessageBox.confirm(msg, "提示", {
				type: "warning",
			}).then(() => {
				delProduct({
					product_id: row.product_id,
				}).then((data) => {
					ElMessage({
						message: "删除成功",
						type: "success",
					});
					self.getData();
				});
			});
		},
		/*修改状态*/
		changeStatus(item, value) {
			let self = this;
			let msg = "";
			if (value == 10) {
				msg = "确认要上架该商品吗?";
			} else {
				msg = "确认要下架该商品吗?";
				if (self.activeName == "recovery") {
					msg = "确认要移动该商品到仓库吗?";
				}
			}
			ElMessageBox.confirm(msg, "提示", {
				type: "warning",
			}).then(() => {
				changeStatus({
					product_id: item.product_id,
					state: value,
				}).then((data) => {
					ElMessage({
						message: "操作成功",
						type: "success",
					});
					self.getData();
				});
			});
		},
	},
};
</script>

<style>

.sku-item {
	display: flex;
	line-height: 2;
	/* border-bottom: 1px solid #eee; */
}

.sku-item-option {
	flex:1;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* .el-table .cell {
	padding: 0;
}

.el-table-small .cell {
	padding: 0;
} */
</style>
